/***********************************************************************
 * Copyright @ 2011 Zhejiang Yutian Technology Co.,Ltd
 * ==================================================================
 * Project:        LaYouNet
 * FileName:       CommonUtils.java
 * Describtion:    文件描述
 * Author:         xufei
 * Create Date:    2014-7-10 下午12:08:42
 *********************************************************************/
package net.hzlj.platform.enterprise.utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.ClipboardManager;

import net.hzlj.platform.enterprise.common.Build;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
/**
 * @ClassName: CommonUtils
 * @Description: 通用工具类
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2016-1-8 14:24:44
 */
public class CommonUtils {

    public static String getCacheRootPath(Context context) {
        return (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !isExternalStorageRemovable()) ? Environment.getExternalStorageDirectory().getPath()
                : context.getFilesDir().getPath();
    }

    public static String setCachePath(Context context, String uniqueName) {
        return getCacheRootPath(context) + uniqueName;
    }

    /**
     * Check if external storage is built-in or removable.
     *
     * @return True if external storage is removable (like an SD card), false
     *         otherwise.
     */
    @TargetApi(9)
    public static boolean isExternalStorageRemovable() {
        if (hasGingerbread()) {
            return Environment.isExternalStorageRemovable();
        }
        return false;
    }

    public static boolean hasFroyo() {
        return android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
    }

    public static boolean hasGingerbread() {
        return android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
    }

    public static boolean hasHoneycomb() {
        return android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
    }

    public static boolean hasHoneycombMR1() {
        return android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1;
    }

    public static boolean hasJellyBean() {
        return android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
    }

    public static String getDeviceID(Context context){
        return ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE))
                .getDeviceId();
    }

    public static String getPackageName(Context context) {
        PackageInfo info;
        String packageName = null;
        try {
            info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            // 当前应用的版本名称
            String versionName = info.versionName;
            // 当前版本的版本号
            int versionCode = info.versionCode;
            // 当前版本的包名
            packageName = info.packageName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return packageName;
    }

    public static String getVersionName(Context context) {
        String versionName = null;
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            versionName = info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionName;
    }

    public static int getVersionCode(Context context){
        PackageInfo info;
        int versionCode = 0;
        try {
            info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            // 当前版本的版本号
            versionCode = info.versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 是否已经安装某应用
     * @param context
     * @param packagename
     * @return
     */
    public static boolean isInstallApp(Context context, String packagename) {
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(
                    packagename, 0);
        } catch (NameNotFoundException e) {
            packageInfo = null;
        }

        return !(packageInfo == null);
    }

    /**
     * 安装apk程序,调用前必须确保当前文件已经存在
     * 若当前设备有root权限,静默安装,否则默认系统提示安装
     * @param context
     * @param filePath
     */
    public static void installApp(Context context, final String filePath) {
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
        context.startActivity(i);
    }

    /**
     * 卸载某应用
     */
    public static void uninstallApp(Context context, String packageName) {
        Uri packageURI = Uri.parse("package:" + packageName);
        Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
        context.startActivity(uninstallIntent);
    }

    /**
     * 打开应用
     * @param context
     * @param packageName
     */
    public static void openApp(Context context, String packageName) {
        PackageManager packManager = context.getPackageManager();
        Intent intent = packManager.getLaunchIntentForPackage(packageName);
        if (intent != null) {//当前程序有Launch入口
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
    }

    /**
     * 复制文本
     * @param context
     * @param text
     */
    public static void copyText(Context context, String text) {
        ClipboardManager cm = (ClipboardManager) context
                .getSystemService(Context.CLIPBOARD_SERVICE);
        cm.setText(text);
    }


    /***
     *  程序是否在运行中
     * @param context
     * @param activityName
     * @return
     */
    public static boolean getLauncherState(Context context, String activityName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> taskList = am.getRunningTasks(1);
        if (taskList != null && !taskList.isEmpty()) {

            for (int i = 0; i < taskList.size(); i++) {
                RunningTaskInfo rti = taskList.get(i);
                if (activityName.equals(rti.baseActivity.getClassName())) {
                    return true;
                }
            }
        }
        return false;
    }

    /***
     *
     * @param paramContext
     * @return
     */
    public static boolean isMobileNet(Context paramContext) {
        NetworkInfo networkInfo = ((ConnectivityManager) paramContext.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (networkInfo == null)
            return false;
        int i = networkInfo.getType();
        if (i == ConnectivityManager.TYPE_MOBILE || i == ConnectivityManager.TYPE_WIMAX) {
            return true;
        } else {
            if (i == ConnectivityManager.TYPE_WIFI) {
                return false;
            }
        }
        return false;
    }

    /***
     * 截图（保存到文件中）
     * @param activity
     * @return
     */
    public static boolean captureScreen(Activity activity,String filePath){
        activity.getWindow().getDecorView().setDrawingCacheEnabled(true);
        Bitmap bmp = activity.getWindow().getDecorView().getDrawingCache();
        boolean flag = false;
        if (bmp != null) {
            try {
                File file = new File(filePath);
                FileOutputStream os = new FileOutputStream(file);
                bmp.compress(Bitmap.CompressFormat.JPEG, 100, os);
                os.flush();
                os.close();
                flag = true;
                //图片压缩
//                Luban.compress(activity,file)
//                        .setMaxWidth(Constant.EXACT_SCREEN_WIDTH)
//                        .setMaxHeight(Constant.EXACT_SCREEN_HEIGHT)
//                        .setMaxSize(100)
//                        .setCompressFormat(Bitmap.CompressFormat.JPEG)
//                        .putGear(Luban.CUSTOM_GEAR)
//                        .asObservable();
            } catch (Exception e) {
            }
        }
        return flag;
    }

}
